package com.example.mapper;

import com.example.entity.PasswordResetToken;
import com.example.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.Optional;

@Mapper
public interface PasswordResetTokenMapper {

    @Insert("INSERT INTO password_reset_tokens (token, user_id, used, created_at, expires_at) " +
            "VALUES (#{token}, #{user.id}, #{used}, #{createdAt}, #{expiresAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(PasswordResetToken token);

    @Select("SELECT t.*, u.* " +
            "FROM password_reset_tokens t " +
            "JOIN users u ON t.user_id = u.id " +
            "WHERE t.token = #{token}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "token", column = "token"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "used", column = "used"),
            @Result(property = "createdAt", column = "created_at"),
            @Result(property = "expiresAt", column = "expires_at"),
            @Result(property = "user", javaType = User.class, column = "user_id",
                    one = @One(select = "com.example.mapper.UserMapper.selectById"))
    })
    Optional<PasswordResetToken> findByToken(String token);

    @Update("UPDATE password_reset_tokens SET used = true WHERE token = #{token}")
    int markAsUsed(String token);

    @Delete("DELETE FROM password_reset_tokens WHERE user_id = #{userId} AND used = false")
    int deleteUnusedTokensByUserId(Long userId);
}